package com.framework.core.tag;


import com.framework.web.sys.domain.Resource;

import java.util.List;
import java.util.Map;


/**
 * 动态菜单栏生成
 * 获取是否有子节点不用查询数据库;
 *
 * @author fusf
 */
public class ListToMenu {

    public static String getAceMultistageTree(Map<Integer, List<Resource>> map) {

        if (map == null || map.size() == 0 || !map.containsKey(0)) {
            return "不具有任何权限,\n请找管理员分配权限";
        }
        StringBuffer menuString = new StringBuffer();
        List<Resource> list = map.get(0);
        int curIndex = 0;
        for (Resource resource : list) {
            if (!ListToMenu.hasSubFunction(resource, map)) {//无子节点情况
                menuString.append("<a href=\"javascript:void(0)\" onclick=\"addTabs('\"+resource.getResourceUrl()+\"','\"+resource.getResourceName()+\"'  class=\"nav-header menu-first collapsed\" data-toggle=\"collapse\" >" + resource.getResourceName() + "</a>");
                menuString.append("<ul id=\"" + resource.getId() + "\" class=\"nav nav-list collapse menu-second\">");
                menuString.append(getSubMenu(resource, 1, map));
                menuString.append("</ul>");
            } else {
                menuString.append("<a href=\"#" + resource.getId() + "\"  class=\"nav-header menu-first collapsed\" data-toggle=\"collapse\" ><i class=\"glyphicon glyphicon-star \"></i>&nbsp;&nbsp;&nbsp;" + resource.getResourceName() + "&nbsp;&nbsp;&nbsp;&nbsp;<i style='color:#CCCCCC' class=\"glyphicon glyphicon-chevron-down\"></i></a>");
                menuString.append("<ul id=\"" + resource.getId() + "\" class=\"nav nav-list collapse menu-second\" >");
                menuString.append(getSubMenu(resource, 1, map));
                menuString.append("</ul>");
            }
            curIndex++;
        }

        return menuString.toString();
    }

    /**
     * 判断是否有子节点
     *
     * @param resource
     * @param map
     * @return
     */
    public static boolean hasSubFunction(Resource resource, Map<Integer, List<Resource>> map) {
        List<Resource> list = map.get(1);
        for (Resource resource1 : list) {
            if (resource.getId().equals(resource.getId())) {
                return true;
            }
        }
        return false;
    }


    private static String getSubMenu(Resource parent, int level, Map<Integer, List<Resource>> map) {
        StringBuffer menuString = new StringBuffer();
        List<Resource> list = map.get(level);
        for (Resource resource : list) {
            if (resource.getParentId().equals(parent.getId())) {
                menuString.append("<li><a href=\"javascript:void(0)\" onclick=\"addTabs('" + resource.getResourceUrl() + "','" + resource.getResourceName() + "')\"><i class=\"\"></i> " + resource.getResourceName() + "</a></li>");
            }
        }
        return menuString.toString();
    }
}